package com.hq.xmind.model;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName DownImage
 * @Description TODO
 * @Author huangzl
 * @Date 2019/2/20 11:20
 * @Version 1.0
 **/
public class DownImage {

    /**
     * 根据地址获得数据的字节流
     *
     * @param strUrl
     *            网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     *
     * @param inStream
     *            输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static byte[] saveToFile(String destUrl) {

        FileOutputStream fos = null;
        BufferedInputStream bis = null;
        HttpURLConnection httpUrl = null;
        URL url = null;
        int BUFFER_SIZE = 1024;
        byte[] buf = new byte[BUFFER_SIZE];
        int size = 0;
        try {
            url = new URL(destUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            InputStream inputStream = httpUrl.getInputStream();


            bis = new BufferedInputStream(inputStream);
            byte[] picture = new byte[bis.available()];
            fos = new FileOutputStream("f:\\haha.jpg");
            while ((size = bis.read(buf)) != -1) {
                fos.write(buf, 0, size);
            }
            fos.flush();
            return picture;
        } catch (IOException e) {
        } finally {
            httpUrl.disconnect();
        }
        return null;
    }

    public static void main(String[] args) {

        saveToFile("http://hqjy-course.oss-cn-shenzhen.aliyuncs.com/18-10-25/85796217.jpg");
    }
}